import { Component, OnInit } from '@angular/core';
import {Message, TreeNode} from 'primeng/primeng';
import {FormBuilder, FormGroup, Validators} from '@angular/forms';
import {PublicService} from '../../services/public.service';
import {RequestForServiceService} from '../request-for-service.service';

@Component({
  selector: 'app-rfs-basal-data',
  templateUrl: './rfs-basal-data.component.html',
  styleUrls: ['./rfs-basal-data.component.scss']
})
export class RfsBasalDataComponent implements OnInit {
  totalRecords;
  rfsbasalModel =[];
    malfunctionDatas: TreeNode[];      // 数据配置树
    titleName: string;                 // 右边表格标题名
    tableDatas: any;                   // 表格数据
    val1: string;                      // 新增启用
    addDisplay: boolean;               // 新增模态框显示控制
    canAdd: boolean;                   // 是都可以新增
    dataName: string;                  // 新增名称字段
    msgs: Message[] = [];              // 表单验证提示
    nodeFather: string;                // 表格中选中的节点的父节点
    nodeDid: string;                   // 表格中选中的节点的did
    nodeDep: string;                   // 表格中选中的节点Dep
    addOrEdit: string;                 // 新增或者编辑按钮显示哪一个
    did: string;                       // 重新请求表格的需要的did
    dep: string;                       // 重新请求表格的需要的dep
    msgPop: Message[];                 // 操作请求后的提示
    selected: any;                     // 被选中的节点
    title: string;                     // 弹出框标题
    dialogDisplay: boolean;            // 删除框控制
    idsArray = [];                     // 数据
    isDisable: boolean;                // 显示设置
    myForm: FormGroup;

    constructor(private rfsService: RequestForServiceService,
                private publicService: PublicService,
                private fb: FormBuilder) { }

    ngOnInit() {
        this.initForm();
        this.getNodeTree();
        this.val1 = '启用';
        this.addDisplay = false;
        this.canAdd = true;
        this.dialogDisplay = false;
        this.isDisable = false;
    }
    getNodeTree(){
      this.publicService.getRfsBasalDatas().subscribe(res => {
        this.malfunctionDatas  = res;
      });
    }
    initForm() {
        this.myForm = this.fb.group({
            'nodeName': ['', Validators.required],
            'nodeActive': '',
            'nodeUnactive': ''
        });
    }
    get isDirty(): boolean {
        let valid = !this.myForm.controls['nodeName'].untouched && !this.myForm.controls['nodeName'].value;
        let validAgain = this.myForm.controls['nodeName'].untouched && !this.myForm.controls['nodeName'].value;
        // let result;
        // console.log('valid----->', valid);
        // console.log('validAgain----->', validAgain);
        return !( valid || validAgain);
    }
    // 组织树懒加载
    nodeExpand(event) {
        if (event.node) {
            this.publicService.getRfsBasalDatas(event.node.did, event.node.dep).subscribe(res => {
                event.node.children  = res;
            });
        }
    }
    // 组织树选中
    NodeSelect(event) {
      console.log(event)
        if (parseInt(event.node.dep) < 2) {
            this.titleName = event.node.label;
            this.nodeFather = event.node.did;
            this.nodeDep = event.node.dep;
            this.did = event.node.did;
            this.dep = event.node.dep;
            this.canAdd = false;
            this.publicService.getRfsBasalDatas(event.node.did, event.node.dep).subscribe(res => {
              this.tableDatas = res;
              this.totalRecords = this.tableDatas.length;
              this.rfsbasalModel = this.tableDatas.slice(0, 10);
            });
        }
    }
  loadCarsLazy(event) {
    setTimeout(() => {
      if (this.tableDatas) {
        this.rfsbasalModel = this.tableDatas.slice(event.first, (event.first + event.rows));
      }
    }, 250);
  }
  cancelMask(bool){
    this.addDisplay = false;
    this.msgs =[];
  }
  refreshDataTable() {
    this.publicService.getRfsBasalDatas(this.did, this.dep).subscribe(res => {
      this.tableDatas = res;
    });
  }

    add() {
        this.myForm.get('nodeName').enable({ onlySelf: true, emitEvent: true});
        this.addDisplay = true;
        this.addOrEdit = 'add';
        this.dataName = '';
        this.title = '新增';
    }

    ansureAddDialog() {
        if ( !this.dataName ) {
            this.msgs = [];
            this.msgs.push({severity: 'error', summary: '错误消息提示', detail: '请填写完整表单'});
        }else {
            this.rfsService.addRfsBasalDatas(this.dataName, this.val1, this.nodeFather, this.nodeDep).subscribe(res => {
                // console.log(res);
                if (res === '00000') {
                    this.msgPop = [];
                    this.msgPop.push({severity: 'success', summary: '消息提示', detail: '新增成功'});
                    // this.refreshDataTable();
                  this.NodeSelect('');
                }else {
                    this.msgPop = [];
                    this.msgPop.push({severity: 'error', summary: '提示消息', detail: '新增失败' + '\n' + res });
                }
            });
            this.addDisplay = false;
        }
    }

    edit(data) {
        // console.log(data);
        this.myForm.get('nodeName').enable({ onlySelf: true, emitEvent: true});
        this.dataName = data.label;
        this.nodeDid = data.did;
        this.nodeDep = data.dep;
        this.addDisplay = true;
        this.addOrEdit = 'edit';
        this.val1 = data.status;
        this.title = '编辑';
    }

    ansureEditDialog() {
        if ( !this.dataName ) {
            this.msgs = [];
            this.msgs.push({severity: 'error', summary: '错误消息提示', detail: '请填写完整表单' });
        }else {
            this.rfsService.editRfsBasalDatas(this.dataName, this.val1, this.nodeDid, this.nodeDep, this.nodeFather).subscribe(res => {
                // console.log(res);
                if (res === '00000') {
                    this.msgPop = [];
                    this.msgPop.push({severity: 'success', summary: '消息提示', detail: '编辑成功'});
                    this.refreshDataTable();
                }else {
                    this.msgPop = [];
                    this.msgPop.push({severity: 'error', summary: '提示消息', detail: '编辑失败' + '\n' + res });
                }
            });
            this.addDisplay = false;
        }
    }


    frezzeOrActive(data) {
        // console.log(data);
        let status = '';
        (data.status === '启用') && ( status = '冻结');
        (data.status === '冻结') && ( status = '启用');
        this.rfsService.editRfsBasalDatas(data.label, status, data.did, data.dep, data.father).subscribe(res => {
            if (res === '00000') {
                this.msgPop = [];
                this.msgPop.push({severity: 'success', summary: '消息提示', detail: status + '成功'});
                this.refreshDataTable();
            }else {
                this.msgPop = [];
                this.msgPop.push({severity: 'error', summary: '提示消息', detail: status + '失败' + '\n' + res });
            }
        });
    }
    delete(data) {
        this.dialogDisplay = true;
        this.idsArray = [];
        this.idsArray.push(data.did);
    }
    sureDelete() {
        this.rfsService.deleteRfsDatas(this.idsArray).subscribe(res => {
            // console.log(res);
            if (res === '00000') {
                this.msgPop = [];
                this.msgPop.push({severity: 'success', summary: '消息提示', detail: '删除成功'});
                this.refreshDataTable();
            }else {
                this.msgPop = [];
                this.msgPop.push({severity: 'error', summary: '提示消息', detail: '删除失败' + '\n' + res });
            }
            this.dialogDisplay = false;
        });
    }
    view(data) {
        // console.log(data);
        this.isDisable = true;
        this.title = '查看';
        this.addDisplay = true;
        this.dataName = data.label;
        this.val1 = data.status;
        this.addOrEdit = '';
        this.myForm.get('nodeName').disable({onlySelf: true, emitEvent: true});
    }

}
